//
//  TTUserInfoViewController.m
//  TaoTuo
//
//  Created by admin on 2019/12/19.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTUserInfoViewController.h"
#import "TTCellArrowModel.h"
#import "TTCellLabelArrowModel.h"
#import "TTCellImageArrowModel.h"
#import "TTCellLabelModel.h"
#import "TTCommonViewCell.h"
#import "TTSetPasswordViewController.h"
#import "TTDianpuShareView.h"
#import "TTAddressManagerViewController.h"
#import "YBImageBrowser.h"
#import "LLImagePicker.h"
#import "OSSImageUploader.h"
#import "WSDatePickerView.h"
#import "TTAlertInputView.h"
#import "TTCompanyInfoViewController.h"

static NSString *cellID = @"set_cell_id";

@interface TTUserInfoViewController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    YBImageBrowser *browser;
    TTCellImageArrowModel *headerArrowModel;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableDictionary *paramsDic;

@end

@implementation TTUserInfoViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self modifyUserInfo];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"个人信息";
    
    [self setupDatas];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.dataArray[section];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTCellModel *model = self.dataArray[indexPath.section][indexPath.row];
    TTCommonViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *arr = self.dataArray[indexPath.section];
    TTCellModel *model = arr[indexPath.row];
    if ([self respondsToSelector:model.selector]) {
        IMP imp = [self methodForSelector:model.selector];
        void(*func)(id, SEL, id) = (void *)imp;
        func(self, model.selector, model);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTCellModel *model = self.dataArray[indexPath.section][indexPath.row];
    if ([model isKindOfClass:[TTCellImageArrowModel class]]) {
        return 60;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 10)];
    view.backgroundColor = kSeparatorColor;
    return view;
}

- (void)modifyUserInfo
{
    if (self.paramsDic.count == 0) {
        return;
    }
    [self.paramsDic setObject:[TTLoginSingle sharedSingle].loginModel.AccountId forKey:@"param.accountId"];
    
    
    [[LLNetworkManagerTool sharedManager] postUrlString:userInfoUpdate_api parameters:self.paramsDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"modifyUserInfoSuccess_key" object:nil];
        [LLPasswordManagerUtilies saveLoginUserInfoWithModel:[TTLoginSingle sharedSingle].loginModel];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:nil];
    
}

// 拍照或选取图片完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    // 图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIView *window = [UIApplication sharedApplication].keyWindow;
    //上传图片到OSS, 添加model
    @weakify(self)
    [MBProgressHUD showLoadingAnimationOnView:window];
    [[OSSImageUploader sharedLoader] asyncUploadImage:image complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
        @strongify(self)
        [MBProgressHUD dismissAnimationOnView:window];
        NSString *urlStr = names.firstObject;
        self->headerArrowModel.rightImageName = urlStr;
        [self.tableView reloadData];
        
        [self->browser hide];
        
        [self.paramsDic setObject:urlStr forKey:@"param.picture"];
        
        [TTLoginSingle sharedSingle].loginModel.Picture = urlStr;
        
    }];
    
}

///点击头像
- (void)headerPictureAction:(TTCellImageArrowModel *)model
{
    headerArrowModel = model;
    
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:model.rightImageName];
    
    browser = [YBImageBrowser new];
    browser.dataSourceArray = @[data];
    [browser show];
    
    @weakify(self)
    [browser.defaultToolViewHandler.topView aspect_hookSelector:@selector(clickOperationButton:) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info, UIButton *btn) {
        @strongify(self)
        [LLImagePicker gotoSystemPhotoLibraryChooseImageAndDelegate:self];
        [self->browser hide];
        
    } error:nil];
    
}

///点击姓名
- (void)realNameAction:(TTCellLabelArrowModel *)model
{
    TTAlertInputView *inputView = [TTAlertInputView createInputViewWithTitle:model.title content:model.content confirmBlock:^(NSString * _Nullable text) {
        model.content = text;
        [self.tableView reloadData];
        
        [self.paramsDic setObject:text forKey:@"param.realName"];
        [TTLoginSingle sharedSingle].loginModel.RealName = text;
    }];
    TYAlertController *alertVC = [TYAlertController alertControllerWithAlertView:inputView];
    alertVC.backgoundTapDismissEnable = YES;
    [self presentViewController:alertVC animated:YES completion:nil];
}

///点击备用手机号
- (void)standbyPhoneNumAction:(TTCellLabelArrowModel *)model
{
    TTAlertInputView *inputView = [TTAlertInputView createInputViewWithTitle:model.title content:model.content confirmBlock:^(NSString * _Nullable text) {
        model.content = text;
        [self.tableView reloadData];
        [self.paramsDic setObject:text forKey:@"param.mobile"];
        [TTLoginSingle sharedSingle].loginModel.Mobile = text;
    }];
    
    TYAlertController *alertVC = [TYAlertController alertControllerWithAlertView:inputView];
    alertVC.backgoundTapDismissEnable = YES;
    [self presentViewController:alertVC animated:YES completion:nil];
}


///点击性别
- (void)genderAction:(TTCellLabelArrowModel *)model
{
    NSArray *array = @[@"女", @"男"];
    TTDianpuShareView *shareView = [TTDianpuShareView shareViewWithTitles:array selectBlock:^(NSInteger index) {
        
        model.content = array[index];
        [self.tableView reloadData];
        
        [self.paramsDic setObject:@(index) forKey:@"param.sex"];
        [TTLoginSingle sharedSingle].loginModel.Sex = [NSString stringWithFormat:@"%ld", index];
        
    }];
    
    
    [LLAnimationAlertView animationAlertViewWithView:shareView animationType:AnimationFromBottom];
}

///点击生日
- (void)birthdayAction:(TTCellLabelArrowModel *)model
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyy-MM-dd"];
    NSString *nowDate = [formatter stringFromDate:[NSDate date]];
    
    @weakify(self)
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay minLimitDateString:@"1900-1-1" maxLimitDateString:nowDate CompleteBlock:^(NSDate *selectDate) {
        @strongify(self)
        NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd"];
        model.content = date;
        [self.tableView reloadData];
        
        [self.paramsDic setObject:date forKey:@"param.birthday"];
        [TTLoginSingle sharedSingle].loginModel.Birthday = date;
    }];
    datepicker.doneButtonColor = kMainColor;
    datepicker.dateLabelColor = kMainColor;
    datepicker.hideBackgroundYearLabel = YES;
    [datepicker show];
}

///点击结婚纪念日
- (void)marriedAction:(TTCellLabelArrowModel *)model
{
    @weakify(self)
    WSDatePickerView *datepicker = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay minLimitDateString:nil maxLimitDateString:nil CompleteBlock:^(NSDate *selectDate) {
        @strongify(self)
        NSString *date = [selectDate stringWithFormat:@"yyyy-MM-dd"];
        model.content = date;
        [self.tableView reloadData];
        
        [self.paramsDic setObject:date forKey:@"param.weddingDay"];
        [TTLoginSingle sharedSingle].loginModel.WeddingDay = date;
    }];
    datepicker.doneButtonColor = kMainColor;
    datepicker.dateLabelColor = kMainColor;
    datepicker.hideBackgroundYearLabel = YES;
    [datepicker show];
}

///点击常用地址
- (void)addressAction:(TTCellLabelArrowModel *)model
{
    TTAddressManagerViewController *addressVC = [[TTAddressManagerViewController alloc] init];
    [self.navigationController pushViewController:addressVC animated:YES];
}

///点击企业信息
- (void)companyAction:(TTCellLabelArrowModel *)model
{
    TTCompanyInfoViewController *companyVC = [[TTCompanyInfoViewController alloc] init];
    [self.navigationController pushViewController:companyVC animated:YES];
}

///点击设置密码
- (void)setPasswordAction:(TTCellLabelArrowModel *)model
{
    TTSetPasswordViewController *pwdVC = [[TTSetPasswordViewController alloc] init];
    [self.navigationController pushViewController:pwdVC animated:YES];
}


- (void)setupDatas
{
    [self.dataArray removeAllObjects];
    
    TTLoginModel *model = [TTLoginSingle sharedSingle].loginModel;
    
    NSMutableArray *arr1 = [NSMutableArray array];
    [arr1 addObject:[TTCellImageArrowModel setModelWithTitle:@"头像" imageName:model.Picture selector:@selector(headerPictureAction:)]];
    
    NSMutableArray *arr2 = [NSMutableArray array];
    [arr2 addObject:[TTCellLabelArrowModel setModelWithTitle:@"真实姓名" content:model.RealName selector:@selector(realNameAction:) contentColor:UIColorHex(666666)]];
    [arr2 addObject:[TTCellLabelArrowModel setModelWithTitle:@"备用手机号" content:model.Mobile selector:@selector(standbyPhoneNumAction:) contentColor:UIColorHex(666666)]];
    [arr2 addObject:[TTCellLabelModel setModelWithTitle:@"注册手机号" content:model.Account contentColor:UIColorHex(666666)]];
    NSString *sex = model.Sex.intValue == 1 ? @"男" : (model.Sex.intValue == 2 ? @"" : @"女");
    [arr2 addObject:[TTCellLabelArrowModel setModelWithTitle:@"性别" content:sex selector:@selector(genderAction:) contentColor:UIColorHex(666666)]];
    [arr2 addObject:[TTCellLabelArrowModel setModelWithTitle:@"生日" content:model.Birthday selector:@selector(birthdayAction:) contentColor:UIColorHex(666666)]];
    [arr2 addObject:[TTCellLabelArrowModel setModelWithTitle:@"结婚纪念日" content:model.WeddingDay selector:@selector(marriedAction:) contentColor:UIColorHex(666666)]];
    
    
    NSMutableArray *arr3 = [NSMutableArray array];
    [arr3 addObject:[TTCellLabelArrowModel setModelWithTitle:@"常用地址" content:nil selector:@selector(addressAction:) contentColor:UIColorHex(666666)]];
    [arr3 addObject:[TTCellLabelArrowModel setModelWithTitle:@"企业信息" content:model.CompanyName selector:@selector(companyAction:) contentColor:UIColorHex(666666)]];
    
    
    NSMutableArray *arr4 = [NSMutableArray array];
    [arr4 addObject:[TTCellLabelArrowModel setModelWithTitle:@"设置密码" content:nil selector:@selector(setPasswordAction:) contentColor:UIColorHex(666666)]];
    
    [self.dataArray addObject:arr1];
    [self.dataArray addObject:arr2];
    [self.dataArray addObject:arr3];
    [self.dataArray addObject:arr4];
    
    [self.tableView reloadData];
    
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kSeparatorColor;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _tableView.separatorColor = kSeparatorColor;
        [_tableView registerClass:[TTCommonViewCell class] forCellReuseIdentifier:cellID];
        _tableView.tableFooterView = [UIView new];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableDictionary *)paramsDic
{
    if (!_paramsDic) {
        _paramsDic = [NSMutableDictionary dictionary];
    }
    return _paramsDic;
}


@end
